<?php

class ChatController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
    	$conversation = Conversation::find();
    	var_dump($conversation); die;
    }

    public function insertAction()
    {

    	//if(!$this->request->isPost) die('Not a post');
    	$conv_id = '549929024153957c1400002c';
    	$conversation = Conversation::findById($conv_id);
    	
    	// INITIALIZE THE DATA
    	$receivers = [1,2,3,4];
    	$sender_id = (int) $this->session->get('user_id');
    	$receivers[] = $sender_id;
    	$message = "Hello";
    	$result = array(); // the result of sending

    	$messages = array(
    			"message_id"=>(string) new MongoId(),
    			"sender_id"=>$sender_id,
    			"message"=>$message,
    			"date_created"=>CURR_DATE,
    			"read"=>0,
    			"cleared"=>0
    			);


    	if(!$conversation)
    	{
    		$conversation = new Conversation();
    		$conversation->date_created = CURR_DATE;
    	}
    	else
    	{

    		$conversation->date_updated = CURR_DATE;
    	
    	}

    		$conversation->receivers = $receivers;
    		$conversation->messages[] = $messages;
    		if(!$conversation->save())
    		{
    			$result['status'] = false;
    			$result['messages'] = "Messages sending failed";

    		}
    		else
    		{
    			$result['status'] = true;
    		}
    	echo json_encode($result);
    	
    	$this->view->disable();
    }

    public function listAction($type='')
    {
    	$conv_id = '549931014153957c1400002f';
    	$conv = Conversation::findById($conv_id);
    	$result['conv_id'] = $conv_id;
    	$result['receivers'] = $conv->receivers;	
    	if(sizeof($conv->messages))
    	{

	    	foreach ($conv->messages as $key => $value){
	 			$result['messages'][] = array(
	 					'message_id'=> $value['message_id'],
	 					"message"=>$value['message']
	 				);   
	 			
	 			
	    	}
    	}


    	echo json_encode($result);
    	$this->view->disable();
    }


}

